package com.dreamlin.app.base.ui

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.StyleRes
import com.dreamlin.app.R
import com.dreamlin.app.common.dp2px

import kotlinx.android.synthetic.main.dialog_common.*

class CommonDialog(context: Context, @StyleRes style: Int) : Dialog(context, style) {

    var action: Int = 0

    constructor(context: Context) : this(context, 0)
    constructor(context: Context, dialogModel: DialogModel) : this(context, 0) {
        this.dialogModel = dialogModel
    }

    private var dialogModel: DialogModel? = null
    var mListener: DialogListener? = null

    init {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
            val view = LayoutInflater.from(context)
                .inflate(R.layout.dialog_common, null)
            setContentView(
                view, ViewGroup.LayoutParams(
                    260f.dp2px().toInt(),
                    ViewGroup.LayoutParams.WRAP_CONTENT
                )
            )
        } else {
            setContentView(R.layout.dialog_common)
        }
    }

    fun update(dialogModel: DialogModel) {
        this.dialogModel = dialogModel
    }

    fun setTips(tips: String) {
        this.dialogModel?.tips = tips
    }

    override fun show() {
        dialogModel?.let {
            tv_title.setTextColor(Color.parseColor(it.titleColor))
            tv_title.text = it.title
            tv_message.setColorTexts(it.tips, it.tipsColor)
            tv_left.setTextColor(Color.parseColor(it.leftColor))
            tv_left.text = it.left
            tv_right.setTextColor(Color.parseColor(it.rightColor))
            tv_right.text = it.right
        }
        super.show()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        tv_left.setOnClickListener {
            mListener?.let {
                it.onCancel(action)
            }
            dismiss()
        }
        tv_right.setOnClickListener {
            mListener?.let {
                it.onConfirm(action)
            }
            dismiss()
        }
    }
}

interface DialogListener {
    fun onCancel(any: Any? = null)

    fun onConfirm(any: Any? = null)
}

data class DialogModel(
    var title: String = "",
    var tips: String = "",
    var left: String = "取消",
    var right: String = "确认",
    val titleColor: String = "#4E4E4E",
    val tipsColor: String = "#4E4E4E",
    val leftColor: String = "#D9D9EC",
    val rightColor: String = "#4272DB"

)